/**  
* @Title: MyInterceptor.java
* @Package com.hjb.service.handlerInterceptor
* @author <a href="mailto:125671254@qq.com">Pan Xinwen</a>panxinwen
* @date 2018年1月9日 下午9:38:32
* @version V1.0  
*/ 
package com.hjb.service.handlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
* @ClassName: MyInterceptor
* @Description: TODO(自定义拦截器：控制用戶授权登录)
* @author <a href="mailto:125671254@qq.com">Pan Xinwen</a>panxinwen
* @date 2018年1月9日 下午9:38:32
*
*/
public class MyInterceptor implements HandlerInterceptor {

	private Logger logger = LoggerFactory.getLogger(MyInterceptor.class);
	
	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.HandlerInterceptor#afterCompletion(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception arg3)
			throws Exception {}

	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.HandlerInterceptor#postHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.web.servlet.ModelAndView)
	 */
	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.HandlerInterceptor#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object)
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // TODO Auto-generated method stub
        logger.info("");
        //获取session
        HttpSession session = request.getSession(true);
        String conurl = request.getContextPath();
        conurl=request.getRequestURI();
        //判断用户ID是否存在，不存在就跳转到登录界面
        if(session.getAttribute("userId") == null&&!conurl.equals("/error")){
            logger.info("------:跳转到login页面！");
            response.sendRedirect(request.getContextPath()+"/admin/login");
            return false;
        }else{
            session.setAttribute("userId", session.getAttribute("userId"));
            return true;
        }

	}

}
